﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Devices.Geolocation;

namespace WP8.Mapas
{
    public partial class LocationTrackingPage : PhoneApplicationPage
    {
        private bool tracking = false;
        private Geolocator geolocator;

        public LocationTrackingPage()
        {
            InitializeComponent();
            //geolocator = App.Geolocator;
        }

        private void TrackLocation_Click(object sender, RoutedEventArgs e)
        {
            if (!tracking)
            {
                geolocator = new Geolocator();
                geolocator.DesiredAccuracy = PositionAccuracy.High;
                geolocator.MovementThreshold = 100;
                geolocator.PositionChanged += geolocator_PositionChanged;
                tracking = true;
            }
            else
            {
                geolocator.PositionChanged -= geolocator_PositionChanged;
                geolocator = null;
                tracking = false;
            }
        }

        void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            if (!App.RunningInBackground)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
                    LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");
                });
            }
            else
            {
                // Show toast if running in background    
                Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
                toast.Content = args.Position.Coordinate.Latitude.ToString("0.00");
                toast.Title = "Location: ";
                toast.NavigationUri = new Uri("/LocationTrackingPage.xaml", UriKind.Relative);
                toast.Show();
            }
        }

    }
}